import os
import win32com.client as win32
from docx import Document
import csv

# 设置请求头，模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

# 查找电脑上的 .doc 和 .docx 文件
def find_doc_files(directory):
    doc_files = []
    docx_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.doc'):
                doc_files.append(os.path.join(root, file))
            elif file.endswith('.docx'):
                docx_files.append(os.path.join(root, file))
    return doc_files, docx_files

# 读取 .docx 文件
def read_docx(file_path):
    doc = Document(file_path)
    content = []
    for para in doc.paragraphs:
        content.append(para.text)
    return content

# 写入 .docx 文件
def write_docx(file_path, content):
    doc = Document()
    for text in content:
        doc.add_paragraph(text)
    doc.save(file_path)

# 读取 .doc 文件
def read_doc(file_path):
    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Visible = False
    doc = word.Documents.Open(file_path)
    content = []
    for para in doc.Paragraphs:
        content.append(para.Range.Text)
    doc.Close(SaveChanges=False)
    word.Quit()
    return content

# 写入 .doc 文件
def write_doc(file_path, content):
    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Visible = False
    doc = word.Documents.Add()
    for text in content:
        doc.Content.InsertAfter(text + '\n')
    doc.SaveAs(file_path)
    doc.Close(SaveChanges=True)
    word.Quit()

# 主函数
def main():
    directory = r'C:\Users\王相辰\Desktop\大一_周记！周记！好多周记！'  
    doc_files, docx_files = find_doc_files(directory)
    
    all_data = []

    # 处理 .docx 文件
    for docx_file in docx_files:
        content = read_docx(docx_file)
        all_data.append(['.docx', docx_file, '\n'.join(content)])
        # 写入一个新的 .docx 文件
        new_docx_file = docx_file.replace('.docx', '_new.docx')
        write_docx(new_docx_file, content)
        print(f"处理并保存了 {docx_file} 到 {new_docx_file}")

    # 处理 .doc 文件
    for doc_file in doc_files:
        content = read_doc(doc_file)
        all_data.append(['.doc', doc_file, '\n'.join(content)])
        # 写入一个新的 .doc 文件
        new_doc_file = doc_file.replace('.doc', '_new.doc')
        write_doc(new_doc_file, content)
        print(f"处理并保存了 {doc_file} 到 {new_doc_file}")

    # 保存所有数据到 CSV 文件
    with open('word_documents_data.csv', 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['File Type', 'File Path', 'Content'])
        writer.writerows(all_data)
    
    print("所有数据已成功保存到 word_documents_data.csv 文件中")

if __name__ == "__main__":
    main()